/**
 * 相册编辑器 - 处理相册的添加和删除功能
 */
class AlbumEditor {
  constructor() {
    this.uploadManager = new UploadManager();
    this.initUI();
    this.setupEventListeners();
  }

  /**
   * 初始化UI元素
   */
  initUI() {
    // 在页面中添加编辑控件
    const albumsContainer = document.querySelector('.albums-container');
    if (!albumsContainer) return;

    // 添加新相册按钮
    const addButtonContainer = document.createElement('div');
    addButtonContainer.className = 'add-album-btn-container text-center my-4';
    addButtonContainer.innerHTML = `
      <button id="addAlbumBtn" class="btn btn-primary">
        <i class="fas fa-plus"></i> 添加新相册
      </button>
    `;
    albumsContainer.parentNode.insertBefore(addButtonContainer, albumsContainer.nextSibling);

    // 添加相册表单模态框
    const modalHTML = `
      <div class="modal fade" id="albumFormModal" tabindex="-1" aria-labelledby="albumFormModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="albumFormModalLabel">添加新相册</h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
            </div>
            <div class="modal-body">
              <form id="albumForm">
                <div class="mb-3">
                  <label for="albumTitle" class="form-label">相册标题</label>
                  <input type="text" class="form-control" id="albumTitle" required>
                </div>
                <div class="mb-3">
                  <label for="albumDate" class="form-label">日期</label>
                  <input type="date" class="form-control" id="albumDate" required>
                </div>
                <div class="mb-3">
                  <label for="albumCategory" class="form-label">分类</label>
                  <select class="form-select" id="albumCategory" required>
                    <option value="">选择分类...</option>
                    <option value="travel">旅行</option>
                    <option value="date">约会</option>
                    <option value="daily">日常</option>
                    <option value="special">特别日子</option>
                  </select>
                </div>
                <div class="mb-3">
                  <label for="albumCover" class="form-label">封面图片</label>
                  <input type="file" class="form-control" id="albumCover" accept="image/*" required>
                  <div class="mt-2" id="coverPreview"></div>
                </div>
                <div class="mb-3">
                  <label class="form-label">相册照片</label>
                  <div class="d-flex align-items-center">
                    <input type="file" class="form-control me-2" id="albumPhotos" accept="image/*" multiple>
                    <button type="button" class="btn btn-outline-primary" id="addPhotosBtn">
                      <i class="fas fa-plus"></i>
                    </button>
                  </div>
                  <div class="row mt-2" id="photosPreview"></div>
                </div>
                <div id="photos-container">
                  <!-- 这里将动态添加照片相关字段 -->
                </div>
              </form>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
              <button type="button" class="btn btn-primary" id="saveAlbumBtn">保存相册</button>
            </div>
          </div>
        </div>
      </div>

      <!-- 删除确认模态框 -->
      <div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-labelledby="deleteConfirmModalLabel" aria-hidden="true">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="deleteConfirmModalLabel">确认删除</h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
            </div>
            <div class="modal-body">
              确定要删除这个相册吗？此操作不可撤销。
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
              <button type="button" class="btn btn-danger" id="confirmDeleteBtn">删除</button>
            </div>
          </div>
        </div>
      </div>
    `;

    // 将模态框添加到页面
    document.body.insertAdjacentHTML('beforeend', modalHTML);

    // 为每个相册添加编辑和删除按钮
    this.addAlbumControls();
  }

  /**
   * 为相册添加编辑和删除控件
   */
  addAlbumControls() {
    const albumCards = document.querySelectorAll('.album-card');
    
    albumCards.forEach(card => {
      // 获取相册ID
      const albumId = card.dataset.id;
      if (!albumId) return;
      
      // 添加控制按钮
      const controlsContainer = document.createElement('div');
      controlsContainer.className = 'album-controls position-absolute top-0 end-0 m-2';
      controlsContainer.innerHTML = `
        <button class="btn btn-sm btn-danger delete-album-btn" data-id="${albumId}">
          <i class="fas fa-trash"></i>
        </button>
      `;
      
      card.style.position = 'relative';
      card.appendChild(controlsContainer);
    });
  }

  /**
   * 设置事件监听器
   */
  setupEventListeners() {
    // 添加相册按钮点击事件
    const addAlbumBtn = document.getElementById('addAlbumBtn');
    if (addAlbumBtn) {
      addAlbumBtn.addEventListener('click', () => {
        // 重置表单
        document.getElementById('albumForm').reset();
        document.getElementById('coverPreview').innerHTML = '';
        document.getElementById('photosPreview').innerHTML = '';
        document.getElementById('photos-container').innerHTML = '';
        
        // 显示模态框
        const modal = new bootstrap.Modal(document.getElementById('albumFormModal'));
        modal.show();
      });
    }

    // 上传封面图片预览
    const albumCover = document.getElementById('albumCover');
    if (albumCover) {
      albumCover.addEventListener('change', (event) => {
        this.previewImage(event.target.files[0], 'coverPreview');
      });
    }

    // 上传相册照片预览
    const albumPhotos = document.getElementById('albumPhotos');
    const addPhotosBtn = document.getElementById('addPhotosBtn');
    if (albumPhotos && addPhotosBtn) {
      addPhotosBtn.addEventListener('click', () => {
        const files = albumPhotos.files;
        if (files.length === 0) return;
        
        // 添加照片预览和标题描述输入框
        this.addPhotoInputs(files);
        
        // 清空文件输入框，以便再次选择文件
        albumPhotos.value = '';
      });
    }

    // 保存相册按钮点击事件
    const saveAlbumBtn = document.getElementById('saveAlbumBtn');
    if (saveAlbumBtn) {
      saveAlbumBtn.addEventListener('click', () => {
        this.saveAlbum();
      });
    }

    // 设置删除相册按钮的事件委托
    document.addEventListener('click', (event) => {
      if (event.target.closest('.delete-album-btn')) {
        const btn = event.target.closest('.delete-album-btn');
        const albumId = btn.dataset.id;
        
        // 设置当前要删除的相册ID
        document.getElementById('confirmDeleteBtn').dataset.id = albumId;
        
        // 显示确认删除模态框
        const modal = new bootstrap.Modal(document.getElementById('deleteConfirmModal'));
        modal.show();
      }
    });

    // 确认删除按钮点击事件
    const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
    if (confirmDeleteBtn) {
      confirmDeleteBtn.addEventListener('click', () => {
        const albumId = confirmDeleteBtn.dataset.id;
        this.deleteAlbum(albumId);
      });
    }
  }

  /**
   * 预览图片
   * @param {File} file - 图片文件
   * @param {string} containerId - 预览容器ID
   */
  previewImage(file, containerId) {
    if (!file) return;
    
    const container = document.getElementById(containerId);
    container.innerHTML = '';
    
    const reader = new FileReader();
    reader.onload = (e) => {
      const img = document.createElement('img');
      img.src = e.target.result;
      img.className = containerId === 'coverPreview' ? 'img-thumbnail mt-2 w-50' : 'img-thumbnail w-100';
      container.appendChild(img);
    };
    reader.readAsDataURL(file);
  }

  /**
   * 添加照片输入框
   * @param {FileList} files - 选择的照片文件
   */
  addPhotoInputs(files) {
    const container = document.getElementById('photos-container');
    const photosPreview = document.getElementById('photosPreview');
    
    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      const photoId = Date.now() + i;
      
      // 添加预览
      const previewCol = document.createElement('div');
      previewCol.className = 'col-md-3 mb-3';
      previewCol.dataset.photoId = photoId;
      
      const reader = new FileReader();
      reader.onload = (e) => {
        previewCol.innerHTML = `
          <div class="position-relative">
            <img src="${e.target.result}" class="img-thumbnail w-100" alt="照片预览">
            <button type="button" class="btn btn-sm btn-danger position-absolute top-0 end-0 m-1 remove-photo" data-photo-id="${photoId}">
              <i class="fas fa-times"></i>
            </button>
          </div>
        `;
      };
      reader.readAsDataURL(file);
      
      photosPreview.appendChild(previewCol);
      
      // 添加照片表单字段
      const photoFieldset = document.createElement('fieldset');
      photoFieldset.className = 'mb-3 photo-fieldset';
      photoFieldset.dataset.photoId = photoId;
      photoFieldset.innerHTML = `
        <input type="hidden" name="photoFile_${photoId}" value="${file.name}" class="photo-file">
        <div class="row">
          <div class="col-md-6">
            <label class="form-label">照片标题</label>
            <input type="text" class="form-control photo-title" required>
          </div>
          <div class="col-md-6">
            <label class="form-label">照片描述</label>
            <input type="text" class="form-control photo-description" required>
          </div>
        </div>
      `;
      
      container.appendChild(photoFieldset);
      
      // 添加删除照片的事件监听
      setTimeout(() => {
        const removeBtn = document.querySelector(`.remove-photo[data-photo-id="${photoId}"]`);
        if (removeBtn) {
          removeBtn.addEventListener('click', () => {
            // 删除预览和表单字段
            const preview = document.querySelector(`.col-md-3[data-photo-id="${photoId}"]`);
            const fieldset = document.querySelector(`.photo-fieldset[data-photo-id="${photoId}"]`);
            
            if (preview) preview.remove();
            if (fieldset) fieldset.remove();
          });
        }
      }, 100);
    }
  }

  /**
   * 保存相册
   */
  async saveAlbum() {
    try {
      const titleInput = document.getElementById('albumTitle');
      const dateInput = document.getElementById('albumDate');
      const categoryInput = document.getElementById('albumCategory');
      const coverInput = document.getElementById('albumCover');
      
      // 表单验证
      if (!titleInput.value || !dateInput.value || !categoryInput.value || !coverInput.files[0]) {
        alert('请填写所有必填字段');
        return;
      }
      
      // 显示加载状态
      const saveBtn = document.getElementById('saveAlbumBtn');
      const originalText = saveBtn.innerHTML;
      saveBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 保存中...';
      saveBtn.disabled = true;
      
      // 1. 上传封面图片
      const coverUploadResult = await this.uploadManager.uploadImage(coverInput.files[0], 'albums');
      
      // 2. 上传相册照片
      const photoFieldsets = document.querySelectorAll('.photo-fieldset');
      const photos = [];
      
      for (const fieldset of photoFieldsets) {
        const photoId = fieldset.dataset.photoId;
        const titleInput = fieldset.querySelector('.photo-title');
        const descriptionInput = fieldset.querySelector('.photo-description');
        
        if (!titleInput.value || !descriptionInput.value) {
          alert('请填写所有照片的标题和描述');
          saveBtn.innerHTML = originalText;
          saveBtn.disabled = false;
          return;
        }
        
        // 获取对应的文件
        const previewEl = document.querySelector(`.col-md-3[data-photo-id="${photoId}"]`);
        if (previewEl) {
          const imgSrc = previewEl.querySelector('img').src;
          
          // 如果是base64格式，表示是新上传的文件
          if (imgSrc.startsWith('data:image')) {
            // 查找对应的文件
            const fileName = fieldset.querySelector('.photo-file').value;
            let photoFile = null;
            
            // 从原始文件输入中查找匹配的文件
            for (let i = 0; i < coverInput.files.length; i++) {
              if (coverInput.files[i].name === fileName) {
                photoFile = coverInput.files[i];
                break;
              }
            }
            
            if (photoFile) {
              // 上传照片
              const photoUploadResult = await this.uploadManager.uploadImage(photoFile, 'albums');
              
              photos.push({
                src: photoUploadResult.filePath,
                title: titleInput.value,
                description: descriptionInput.value
              });
            }
          }
        }
      }
      
      // 3. 构建相册数据
      const albumData = {
        title: titleInput.value,
        date: dateInput.value,
        category: categoryInput.value,
        cover: coverUploadResult.filePath,
        count: photos.length,
        photos: photos
      };
      
      // 4. 保存相册数据
      const result = await this.uploadManager.addAlbum(albumData);
      
      // 5. 处理结果
      if (result.success) {
        alert('相册添加成功');
        
        // 关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('albumFormModal'));
        modal.hide();
        
        // 刷新页面以显示新相册
        window.location.reload();
      } else {
        throw new Error(result.message || '添加相册失败');
      }
    } catch (error) {
      console.error('保存相册出错:', error);
      alert(`添加相册失败: ${error.message}`);
      
      // 恢复按钮状态
      const saveBtn = document.getElementById('saveAlbumBtn');
      saveBtn.innerHTML = '<i class="fas fa-save"></i> 保存相册';
      saveBtn.disabled = false;
    }
  }

  /**
   * 删除相册
   * @param {string} albumId - 要删除的相册ID
   */
  async deleteAlbum(albumId) {
    try {
      // 显示加载状态
      const confirmBtn = document.getElementById('confirmDeleteBtn');
      const originalText = confirmBtn.innerHTML;
      confirmBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 删除中...';
      confirmBtn.disabled = true;
      
      // 调用删除API
      const result = await this.uploadManager.deleteAlbum(albumId);
      
      // 处理结果
      if (result.success) {
        // 关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('deleteConfirmModal'));
        modal.hide();
        
        // 从页面中移除相册
        const albumCard = document.querySelector(`.album-card[data-id="${albumId}"]`);
        if (albumCard) {
          albumCard.remove();
        } else {
          // 如果找不到对应元素，刷新页面
          window.location.reload();
        }
        
        alert('相册已成功删除');
      } else {
        throw new Error(result.message || '删除相册失败');
      }
    } catch (error) {
      console.error('删除相册出错:', error);
      alert(`删除相册失败: ${error.message}`);
      
      // 恢复按钮状态
      const confirmBtn = document.getElementById('confirmDeleteBtn');
      confirmBtn.innerHTML = originalText;
      confirmBtn.disabled = false;
    }
  }
}

// 当文档加载完成时初始化编辑器
document.addEventListener('DOMContentLoaded', () => {
  // 检查是否在相册页面
  if (document.querySelector('.albums-container')) {
    new AlbumEditor();
  }
}); 